<template>
  <div class="equipTypeSum" ref="equipTypeSum"></div>
</template>

<script lang="ts">
export default {
  name: "equipTypeSum"
};
</script>

<script setup lang="ts">
import { ECharts } from "echarts";
import echarts from "/@/plugins/echarts";
import { onMounted, nextTick, ref, watch } from "vue";
import { tryOnUnmounted, useTimeoutFn } from "@vueuse/core";

import {
  addResizeListener,
  removeResizeListener
} from "element-plus/lib/utils/resize-event";

import { deviceProcess } from "/@/api/analysis";
import { storageLocal } from "/@/utils/storage";

const props = defineProps({
  typeId: {
    type: String,
    default: ""
  }
});
// const emit = defineEmits(["clickItem"]);

const equipTypeSum = ref<HTMLElement | null>(null) as any;

let echartInstance: ECharts;

const initChart = (xAxisData, data) => {
  if (!echartInstance) {
    return;
  }

  let timelineData = [];
  let timelineConf = [];
  let seriesData = [
    {
      name: "未启动",
      // data: [100, 120, 123, 134, 177],
      type: "bar",
      barWidth: "20px",
      stack: "total",
      yAxisIndex: 0
      // label: {
      //   show: true,
      //   position: "top"
      // }
    },
    {
      name: "处理中",
      // data: [100, 120, 123, 134, 177],
      type: "bar",
      barWidth: "20px",
      stack: "total",
      yAxisIndex: 0
      // label: {
      //   show: true,
      //   position: "top"
      // }
    },
    {
      name: "已完成",
      // data: [150, 230, 135, 147, 260],
      data: null,
      type: "bar",
      barWidth: "20px",
      yAxisIndex: 0,
      stack: "total"
      // label: {
      //   show: true,
      //   position: "top"
      // }
    },
    {
      name: "",
      color: "transparent",
      // data: [317, 120, 46, 89, 140, 12, 46, 89, 140, 100, 120, 123, 134], // 总和
      type: "bar",
      barWidth: "20px",
      barGap: "-100%",
      label: {
        show: true,
        color: "#545578",
        position: "top"
      }
    }
  ];
  // 根据每页显示条数确定需要分几页展示
  let numPerPageLimit = 6;
  let page = Math.ceil(data[0].length / numPerPageLimit);
  for (let i = 0; i < page; i++) {
    let start = i * numPerPageLimit;
    let end = (i + 1) * numPerPageLimit;
    let seriesItem = []; // series 数据
    data.forEach(item => {
      seriesItem.push({ data: item.slice(start, end) });
    });
    timelineConf.push({
      xAxis: { data: xAxisData.slice(start, end) },
      series: seriesItem
    });
    timelineData.push("item" + i);
  }
  let option = {
    // title: {
    //   text: "合同/标段总提单量概览",
    //   textStyle: {
    //     fontSize: 16,
    //     fontWeight: "normal",
    //     padding: 10
    //   }
    // },
    color: ["#5298FF", "#FFD765", "#85DF00", "#FE931A"],
    grid: {
      left: 44,
      right: 44,
      top: 44,
      bottom: 40
    },
    legend: {
      left: 44,
      padding: [8, 5, 4, 0],
      itemWidth: 8,
      itemHeight: 8
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        lineStyle: {
          color: "rgba(136,153,244,0.6)"
        }
      },
      formatter: function (params) {
        var res = "<div><p>" + params[0].name + "</p ></div>";
        for (let i = 0; i < params.length - 1; i++) {
          res +=
            "<p><font color=" +
            params[i].color +
            ">● " +
            "</font>" +
            params[i].seriesName +
            "：" +
            params[i].data +
            "</p >";
        }
        return res;
      }
    },
    xAxis: {
      type: "category",
      // triggerEvent: true,
      // axisTick: {
      //   alignWithLabel: true
      // },
      boundaryGap: true,
      data: null,
      axisTick: { show: false },
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(160,185,252,0.6)"
        }
      },
      axisLabel: {
        margin: 4,
        textStyle: {
          color: "#545578",
          lineHeight: 17
        },
        formatter: function (params) {
          var newParamsName = "";
          var paramsNameNumber = params.length;
          var provideNumber = 4; //一行显示多少个文字
          var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
          if (paramsNameNumber > provideNumber) {
            for (var p = 0; p < rowNumber; p++) {
              var tempStr = "";
              var start = p * provideNumber;
              var end = start + provideNumber;
              if (p == rowNumber - 1) {
                tempStr = params.substring(start, paramsNameNumber);
              } else {
                tempStr = params.substring(start, end) + "\n";
              }
              newParamsName += tempStr;
            }
          } else {
            newParamsName = params;
          }
          return newParamsName;
        }
      }
    },
    yAxis: {
      type: "value",
      key: "y0",
      splitNumber: 5,
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(160,185,252,0.6)"
        }
      },
      splitLine: {
        show: false
      },
      axisLabel: {
        show: true,
        color: "#545578",
        fontSize: 12
      },
      boundaryGap: [0, "20%"]
    },
    series: seriesData,
    timeline: {
      axisType: "category",
      show: false,
      autoPlay: true,
      playInterval: 3000,
      data: timelineData
    },
    options: timelineConf
  };
  echartInstance.setOption(option);
};

function initechartInstance(xAxisData, seriesData) {
  const echartDom = document.querySelector(".equipTypeSum");
  if (!echartDom) return;
  // @ts-ignore
  echartInstance = echarts.init(echartDom);
  echartInstance.clear(); //清除旧画布 重新渲染

  initChart(xAxisData, seriesData);

  // echartInstance.on("click", function (params) {
  //   let value = "" as any;
  //   if (params.componentType == "xAxis") {
  //     value = params.value;
  //   } else {
  //     value = params.name;
  //   }
  //   console.log(11, "********", value, params);
  //   emit("clickItem", value);
  // });
}

const getData = async (module?) => {
  try {
    let sectionId = storageLocal.getItem("sectionInfo")?.id;
    let projectManageId = storageLocal.getItem("projectInfo")?.id;
    const { code, data } = await deviceProcess({
      sectionId,
      projectManageId,
      module: module || "1"
    });
    if (code === 200) {
      let name = [];
      let list = [[], [], [], [], []];
      data.forEach(item => {
        name.push(item.stageName);
        let d = item.noStartDoingComplete;
        list[0].push(d.taskNoStartTotal);
        list[1].push(d.taskDoingTotal);
        list[2].push(d.taskCompleteTotal);
        list[3].push(
          d.taskNoStartTotal + d.taskDoingTotal + d.taskCompleteTotal
        );
      });
      let xAxisData = name;
      let dataList = list;
      // xAxisData = [
      //   "阶段一",
      //   "阶段2",
      //   "阶段3",
      //   "阶段四",
      //   "阶段5",
      //   "标段6",
      //   "阶段7",
      //   "标段8"
      // ];
      // dataList = [
      //   [10, 16, 23, 56, 123, 86, 70, 156],
      //   [20, 23, 23, 23, 43, 23, 123, 233],
      //   [50, 30, 30, 56, 90, 89, 65, 67]
      // ];
      nextTick(() => {
        initechartInstance(xAxisData, dataList);
      });
    }
  } catch (err) {
    console.log(err);
  }
};

getData();

onMounted(() => {
  nextTick(() => {
    addResizeListener(equipTypeSum.value, resetRender);
  });
  // useEventListener("resize", () => {
  //   console.log("resize");
  //   if (!echartInstance) return;
  //   useTimeoutFn(() => {
  //     echartInstance.resize();
  //   }, 180);
  // });
});

watch(
  () => props.typeId,
  newVal => {
    getData(newVal);
  }
);

const resetRender = () => {
  if (!echartInstance) return;
  useTimeoutFn(() => {
    echartInstance.resize();
  }, 180);
};

tryOnUnmounted(() => {
  if (!echartInstance) return;
  echartInstance.dispose();
  echartInstance = null;
  removeResizeListener(equipTypeSum.value, resetRender);
});
</script>

<style lang="scss" scoped>
.equipTypeSum {
  width: 100%;
  height: 100%;
}
</style>
